<template>
  <el-radio-group v-model="dicSelect" @change="handleChange">
    <el-radio-button key="" label="" v-if="showAll">全部</el-radio-button>
    <el-radio-button
      v-for="item in options"
      :key="item.key"
      :label="item.key"
    >{{item.value}}</el-radio-button>
  </el-radio-group>
</template>

<script setup>
import {ref, watch, onBeforeMount, onUnmounted} from 'vue';
import {useDictionaryStore} from '@/pinia/modules/dictionary';
import {emitter} from "@/utils/bus";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  options: Array,
  dicCode: String,
  showAll: {
    type: Boolean,
    default: true
  },
});

const dictionaryStore = useDictionaryStore();
const options = ref([]);
const dicSelect = ref(props.modelValue || '');

const init = (data) => {
  dicSelect.value = (data.modelValue || '') + '';

  if (data.options && data.options.length > 0) {
    options.value = data.options;
  } else if (data.dicCode) {
    loadDicAndShow(data.dicCode);
    emitter.off('dictionary.change');
    emitter.on('dictionary.change', () => {
      loadDicAndShow(data.dicCode);
    });
  }
};

const handleChange = (event) => {
  emit('update:modelValue', dicSelect.value);
  emit('change', event);
};

const loadDicAndShow = async(dicCode) => {
  if ((dicCode || '') === '') {
    options.value = [];
  } else {
    options.value = await dictionaryStore.getDictionary(dicCode)
  }
};

watch(() => props, (data) => {
  init(data);
}, {deep: true});

onBeforeMount(() => {
  init(props);
});

onUnmounted(() => {
  if (props.dicCode) {
    emitter.off('dictionary.change');
  }
});
</script>